// © 2009 Microsoft Corporation.  All rights reserved.
# region Namespace

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Collections.Specialized;
using System.Data;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Xml;


using AjaxControlToolkit;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.RiskService;
using UTL = Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
using Microsoft.Security.Application;
using System.EnterpriseServices;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;

# endregion

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Risks
{
    public partial class SubmitRisk : System.Web.UI.Page
    {
        #region Page Event Handling

        protected void Page_Load(object sender, EventArgs e)
        {
            txtRiskWt.Attributes.Add("onchange", "return CheckForInputWtOnChange('" + txtRiskWt.ClientID + "', null);");

            // Role CHECKING on every page request.
            if (!
                (
                // Not checking for Risk manager because Risk user is child of Risk manager.  
                // Parent inherits childs permission.                     
                     this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                  || this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString())
                )
               )
                Response.Redirect("../Errors/403.htm", true);
            else
            {
                if (
               (
                    (!(
                    this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                 || this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskManager"].ToString()))
                 )
                 &&
                 (this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString()))
               )
              )
                    ViewState["readOnlyORnoAccess"] = true; // The user is niether RiskUser or RiskManager and IS TTU.
                else
                    ViewState["readOnlyORnoAccess"] = false; // The user is either RM, RU and NOT TTU.
            }

            if (!IsPostBack)
            {
                //CHECK for QueryString parameter. That will flag for new or old risk.
                if (Request.QueryString["RiskID"] == null)
                {
                    // New Risk Use case when the user is not RM or RU.
                    if ((bool)ViewState["readOnlyORnoAccess"] == true)
                        Response.Redirect("../Errors/403.htm", true);

                    // True - means New RISK.
                    DisplayRiskData(true); // First tab only.
                    // Needed for organization & contacts.
                    BindDefaultNodes(false);

                    // Hide the chart
                    chartCRV.Visible = false;
                    lblChartMessage.Visible = true;
                    lblchartfliter.Visible = false;

                } // End of new Risk.
                else
                {
                    ViewState["RiskID"] = int.Parse(Request.QueryString["RiskID"].ToString()); // Only int.

                    // Check the user permission to view the Risk if the user is
                    // not RM or RU. TBD
                    // Bind only if RM or RU.
                    if ((bool)ViewState["readOnlyORnoAccess"] == false)
                    {
                        // Existing Risk.
                        DisplayRiskData(false); // First tab only.
                        DataBindIncidents(); // Second tab.
                        BindHistory(); // Third tab.                        
                    }
                    else
                    {
                        if (!UserHasAcccess())
                            Response.Redirect("../Errors/403.htm", true); // TTU does not have permissions.

                        // Existing Risk.
                        DisplayRiskData(false); // First tab only.
                    }

                    // Display the Chart
                    chartCRV.Visible = true;
                    lblchartfliter.Visible = true;
                    // Bind data to Chart.
                    BindToChart();
                }
                // Needed for both new and old.
                GetRootLevelBind();
                treeOrganization.ExpandDepth = 1;
            } // exiting RISK.

            // Role based check for enabling UI elemenets.
            RoleBasedCheck();
        } // End of Page load.        

        /// <summary>
        /// Handles Submit event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitRisk_Click(object sender, EventArgs e)
        {
            string submittedbyFullName = string.Empty;
            int riskID;
            int result;
            RiskService.RiskData riskInstance = null;

            try
            {
                if (!Page.IsValid)
                    throw new Exception("Custom:" + UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "SERVER_VALIDATIONFAILED"));

                riskInstance = new RiskData();

                // Create Risk Instance & populate the values.
                riskInstance.Title = txtTitle.Text.Trim();
                riskInstance.Desc = txtDescription.Text.Trim();
                riskInstance.DataClassificationID = int.Parse(drpDataClassification.SelectedValue);
                riskInstance.PIIID = int.Parse(drpPII.SelectedValue);
                riskInstance.RiskOrigin = int.Parse(drpRiskOrgin.SelectedValue);
                riskInstance.Status = int.Parse(drpRiskStatus.SelectedValue);

                // Is validated by Triage
                if (chkTriage.Checked)
                    riskInstance.RiskValidatedByTriage = 1;
                else
                    riskInstance.RiskValidatedByTriage = 0;

                // Bind Risk fields to risk object.
                riskInstance.CurrentImpactValue = int.Parse(drpCurrentImpact.SelectedValue);
                riskInstance.CurrentFrequencyValue = int.Parse(drpCurrentFrequency.SelectedValue);
                riskInstance.CurrentControlAffectivenessValue = int.Parse(drpCurrentControlAffectiveness.SelectedValue);
                riskInstance.CurrentImapctJustification = txtboxCurrentImpact.Text.Trim();
                riskInstance.CurrentFrequencyJustification = txtCurrentFrequency.Text.Trim();
                riskInstance.CurrentControlAffectivenessJustification = txtCurrentCF.Text.Trim();
                riskInstance.TargetImpactValue = int.Parse(drpTargetImpact.SelectedValue);
                riskInstance.TargetFrequencyValue = int.Parse(drpTargetControlFrequency.SelectedValue);
                riskInstance.TargetControlAffectivenessValue = int.Parse(drpCFTarget.SelectedValue);
                riskInstance.TargetImpactJustification = txtTargetImpactJustification.Text.Trim();
                riskInstance.TargetFrequencyJustification = txtTargetFreqJustification.Text.Trim();
                riskInstance.TargetControlAffectivenessJustification = txtTargetCFjustification.Text.Trim();

                // Check for UnKnown - targetCRV
                if ((string.IsNullOrEmpty(lblTargteRiskRatingValue.Text)) || (lblTargteRiskRatingValue.Text.Equals(ConfigurationManager.AppSettings["DefaultTextRatings"].ToString().Trim())))
                    riskInstance.TargetCalculatedRiskValue = 0;
                else
                    riskInstance.TargetCalculatedRiskValue = int.Parse(lblTargteRiskRatingValue.Text);

                // Check for UnKnown - currentCRV
                if ((string.IsNullOrEmpty(lblCurrentCRV.Text)) || (lblCurrentCRV.Text.Equals(ConfigurationManager.AppSettings["DefaultTextRatings"].ToString().Trim())))
                    riskInstance.CurrentCalculatedRiskValue = 0;
                else
                    riskInstance.CurrentCalculatedRiskValue = int.Parse(lblCurrentCRV.Text);

                // Target Risk Rating.
                if (lblTargetRiskRating.Text.Equals(ConfigurationManager.AppSettings["DefaultTextRatings"].ToString().Trim()))
                    riskInstance.TargetRiskRating = null;
                else
                    riskInstance.TargetRiskRating = lblTargetRiskRating.Text.Trim().ToString();

                // Current Risk Rating.
                if (lblCurrentRiskRating.Text.Equals(ConfigurationManager.AppSettings["DefaultTextRatings"].ToString().Trim()))
                    riskInstance.TargetRiskRating = null;
                else
                    riskInstance.CurrentRiskRating = lblCurrentRiskRating.Text.Trim().ToString();

                // Notes and Comments
                riskInstance.Note = txtNewNote.Text.Trim();
                riskInstance.OwnersComment = txtComments.Text.Trim();

                riskInstance.Alias = ((CISF.Security.Principal.CISFIdentity)User.Identity).Name;
                if (ViewState["RiskID"] == null)
                    riskInstance.SubmittedBy = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                else
                    riskInstance.UpdatedBy = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;

                if (ViewState["RiskID"] == null)
                {
                    if (int.Parse(ViewState["RiskConfiguration"].ToString()) == 1)
                        riskInstance.RiskManagerID = -1;// No Need. The Manager will come from Configuration.
                    else
                        riskInstance.RiskManagerID = int.Parse(drpManager.SelectedValue);
                }
                else
                {
                    riskInstance.RiskManagerID = int.Parse(drpManager.SelectedValue);
                }

                if (ViewState["contact"] != null)
                    riskInstance.Contacts = ViewState["contact"].ToString();
                else
                    riskInstance.Contacts = string.Empty;

                riskInstance.OERMClassifications = GetConcatenatedString(lstOERMClassification);
                riskInstance.Locations = GetConcatenatedString(lstAffectedLocations);
                riskInstance.RiskGroup = GetConcatenatedString(lstRiskGroup);

                if (ViewState["organization"] != null)
                    riskInstance.Organizations = ViewState["organization"].ToString();
                else
                    riskInstance.Organizations = null;

                //Risk Manager Configuration
                riskInstance.RiskConfigurationFlag = int.Parse(ViewState["RiskConfiguration"].ToString());

                // Risk Wt
                riskInstance.RiskPriortizedWt = Decimal.Parse(txtRiskWt.Text.Trim());
                if (!string.Equals(lblPRCV.Text.Trim(), ConfigurationManager.AppSettings["DefaultTextRatings"].ToString()))
                    riskInstance.RiskPriortizedCRV = Decimal.Parse(lblPRCV.Text.Trim());
                else
                    riskInstance.RiskPriortizedCRV = -1;

                // Call SOA Layer for the submission of risk.
                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();

                // Is it new risk?
                if (ViewState["RiskID"] == null)
                {
                    riskID = riskServiceClient.SubmitRisk(out submittedbyFullName, riskInstance);
                    // Store it in ViewSatte for other tabs to use.
                    ViewState["RiskID"] = riskID.ToString();
                    txtRiskID.Text = riskID.ToString();

                    // By & Date.
                    lblsubmittedby.Text = AntiXss.HtmlEncode(submittedbyFullName.Trim());
                    lblDelimitor.Visible = true;
                    lblSubmittedDate.Text = DateTime.UtcNow.ToString();
                    
                    // Check and Bind Risk Manager for the Risk.
                    ListItem manager = riskServiceClient.GetRiskManager(int.Parse(ViewState["RiskID"].ToString()));                    

                    // Check and Bind RM for Risk.                    
                    ListItem managerinList = drpManager.Items.FindByValue(manager.Value.ToString());
                    if (managerinList != null)
                    {
                        drpManager.SelectedItem.Selected = false;
                        managerinList.Selected = true;
                    }                                        
                    
                    //Read the Resource file.      
                    UTL.Utility.ShowMessage((MasterPage)Master, UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "RISK_INSERTSUCCESS"), "Information", false);

                    // Show the other two tabs.
                    tabRiskHistory.Visible = true;
                    tabRiskIncidents.Visible = true;
                    tabRiskIncidents.Enabled = true; // Some bug in AJAX, you need to do this.                    
                    
                    DataBindIncidents(); // Second tab.
                    BindHistory(); // Third tab.                                       
                }
                else
                {
                    riskInstance.RiskID = int.Parse(ViewState["RiskID"].ToString());
                    result = riskServiceClient.UpdateRisk(riskInstance);
                    Page pge = (Page)this.Page;
                    // Read the Resource file.
                    UTL.Utility.ShowMessage((MasterPage)Master, UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "RISK_UPDATESUCCESS"), "Information", false);

                    BindHistory(); // Refresh History.                     
                }

                // Role based access & correct.
                if (this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskManager"].ToString()))
                {
                    createViewTasks.RiskID = int.Parse(ViewState["RiskID"].ToString());
                    createViewTasks.LoadData();
                    createViewTasks.DoDataBind();
                    // Show tab.
                    tabTaskManagement.Visible = true;
                }

                // Show Chart.
                chartCRV.Visible = true;
                lblchartfliter.Visible = true;
                lblChartMessage.Visible = false;
                
                // Show Manager and bind.
                drpManager.Visible = true;
                lblRiskManager.Visible = true;
                lblManager.Visible = true;

                // Display data.
                BindToChart();

                // Rebind the Notes to grid and clean up the note area.
                NoteData[] note = riskServiceClient.GetNotes(int.Parse(ViewState["RiskID"].ToString()));
                if (note.Length > 0)
                {
                    gridRiskNotes.DataSource = riskServiceClient.GetNotes(int.Parse(ViewState["RiskID"].ToString()));
                    gridRiskNotes.DataBind();
                    txtNewNote.Text = string.Empty;
                    lblEarlierNotes.Visible = true;
                }
                // Default to First tab.
                tabDetailData.ActiveTabIndex = 0;

                // Close the service.
                riskServiceClient.Close();
            }
            catch (Exception exObject)
            {
                char[] err = { ':' };
                string[] messages = exObject.Message.Split(err);
                if (messages[0].Trim().ToString() == "Custom")
                {
                    Page pge = (Page)this.Page;
                    Type cstype = this.GetType();
                    // Display the message.
                    UTL.Utility.ShowMessage((MasterPage)Master, messages[1], "Error", true);
                    Server.ClearError();
                }
                else
                    throw exObject;
            }
        }

        /// <summary>
        /// Bind to ListBox and also selected the items based on - selectedIndexes.
        /// </summary>
        /// <param name="lstControl"></param>
        /// <param name="collection"></param>
        private void BindToList(ListBox lstControl, ListItem[] collection, int[] selectedIndexes)
        {
            // Bind to the collection.
            lstControl.Items.AddRange(collection);

            // Select the items from collection based on selectedIndexes int array.
            ListItem temp = null;
            if (selectedIndexes != null)
            {
                // Check for Zero Index.
                if (selectedIndexes.GetUpperBound(0) >= 0)
                {
                    foreach (int selected in selectedIndexes)
                    {
                        temp = lstControl.Items.FindByValue(selected.ToString());
                        if (temp != null)
                            temp.Selected = true;
                    }
                }
            }
        }

        protected void drpCurrentImpact_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(true);

            // Business decision to un check validated by triage CheckBox if
            // current I,F,C ratings change by user.
            if (chkTriage.Checked)
                chkTriage.Checked = false;
        }

        protected void drpCurrentFrequency_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(true);

            // Business decision to un check validated by triage CheckBox if
            // current I,F,C ratings are changed by user.
            if (chkTriage.Checked)
                chkTriage.Checked = false;
        }

        protected void drpCurrentControlAffectiveness_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(true);

            // Business decision to un check validated by triage CheckBox if
            // current I,F,C ratings change.
            if (chkTriage.Checked)
                chkTriage.Checked = false;
        }

        protected void drpTargetImpact_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(false);
        }

        protected void drpTargetCA_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(false);
        }

        protected void drpTargetFrequency_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Bind the Current CRV and Risk Rating values 
            BindRatings(false);
        }

        #endregion

        #region Bind Data to UI Controls
        /// <summary>
        ///  This method is called to bind data to UI based on of the risk is new or exsitng risk for edit.
        /// </summary>
        /// <param name="IsNewRisk"></param>
        private void DisplayRiskData(bool IsNewRisk)
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // Declare local variables.
            RiskService.RiskInformation existingRiskInstance = null;
            ListItem[] lstcollection = null;
            int defaultValueUI = -1;
            int defaultValueRiskStatus = -1;

            // If not new, then get the Risk Information object.
            if (!IsNewRisk)
                existingRiskInstance = riskServiceClient.GetRiskInformation(int.Parse(ViewState["RiskID"].ToString()));
            
            // Bind PII drop down list            
            lstcollection = riskServiceClient.GetPIIOptions();
            BindToDropDownList(drpPII, lstcollection);
            if (!IsNewRisk)
                drpPII.SelectedValue = existingRiskInstance.PIIID.ToString();

            // Bind Data to OERM collection.
            lstcollection = riskServiceClient.GetOERMClassifications();
            if (IsNewRisk)
                BindToList(lstOERMClassification, lstcollection, null);
            else
                BindToList(lstOERMClassification, lstcollection, existingRiskInstance.OERMClassification);

            lstcollection = null;
            // Bind Data to Risk Group Collection.
            lstcollection = riskServiceClient.GetRiskGroups();
            if (IsNewRisk)
            {
                BindToList(lstRiskGroup, lstcollection, null);
                defaultValueUI = int.Parse(ConfigurationManager.AppSettings["DefaultSelectionValueRiskGroup"].ToString());
                lstRiskGroup.SelectedValue = defaultValueUI.ToString();
            }
            else
                BindToList(lstRiskGroup, lstcollection, existingRiskInstance.RiskGroups);

            lstcollection = null;
            // Bind to Locations.
            lstcollection = riskServiceClient.GetLocations();
            if (IsNewRisk)
                BindToList(lstAffectedLocations, lstcollection, null);
            else
                BindToList(lstAffectedLocations, lstcollection, existingRiskInstance.Geography);

            // Bind data to Data Classification.
            lstcollection = riskServiceClient.GetDataClassifications();
            BindToDropDownList(drpDataClassification, lstcollection);
            if (!IsNewRisk)
                drpDataClassification.SelectedValue = existingRiskInstance.DataClassificationID.ToString();


            // Risk Origin
            lstcollection = riskServiceClient.GetRiskOrigin();
            BindToDropDownList(drpRiskOrgin, lstcollection);
            if (!IsNewRisk)
                drpRiskOrgin.SelectedValue = existingRiskInstance.RiskOrigin.ToString();
            else
            {
                // The UI does not know which value defaults when entering from RM UI. 
                // So we use Web.Config to store this value and is used to flag when we display.
                defaultValueUI = int.Parse(ConfigurationManager.AppSettings["DefaultRiskOrginValueforUI"].ToString());
                drpRiskOrgin.SelectedValue = defaultValueUI.ToString();
            }

            //Risk Status
            lstcollection = riskServiceClient.GetRiskStatusOptions();
            BindToDropDownList(drpRiskStatus, lstcollection);
            if (!IsNewRisk)
                drpRiskStatus.SelectedValue = existingRiskInstance.Status.ToString();
            else
            {
                // The UI does not know which value defaults when entering from RM UI. 
                // So we use Web.Config to store this value and is used to flag when we display.
                defaultValueRiskStatus = int.Parse(ConfigurationManager.AppSettings["DefaultRiskStatusValueforUI"].ToString());
                drpRiskStatus.SelectedValue = defaultValueRiskStatus.ToString();
            }

            // Impact
            lstcollection = riskServiceClient.GetRiskImpactOptions();
            BindToDropDownList(drpTargetImpact, lstcollection);
            BindToDropDownList(drpCurrentImpact, lstcollection);

            // Frequency
            lstcollection = riskServiceClient.GetRiskFrequencyOptions();
            BindToDropDownList(drpCurrentFrequency, lstcollection);
            BindToDropDownList(drpTargetControlFrequency, lstcollection);

            // Control Affectiveness
            lstcollection = riskServiceClient.GetRiskCAOptions();
            BindToDropDownList(drpCFTarget, lstcollection);
            BindToDropDownList(drpCurrentControlAffectiveness, lstcollection);

            //Close the service now since we have all the data that we need to bind to UI.
            riskServiceClient.Close();

            // Call SOA layer for Manager List
            GetDataForManager();

            if (!IsNewRisk)
            {
                // Check and Bind RM for Risk.
                ListItem manager = drpManager.Items.FindByValue(existingRiskInstance.RiskManagerID.ToString());
                if (manager != null)
                    manager.Selected = true;

                // Bind data to IFC values.
                drpCurrentImpact.SelectedValue = existingRiskInstance.CurrentImpactValue.ToString();
                drpCurrentFrequency.SelectedValue = existingRiskInstance.CurrentFrequencyValue.ToString();
                drpCurrentControlAffectiveness.SelectedValue = existingRiskInstance.CurrentControlAffectivenessValue.ToString();

                // target data to IFC values.
                drpTargetImpact.SelectedValue = existingRiskInstance.TargetImpactValue.ToString();
                drpTargetControlFrequency.SelectedValue = existingRiskInstance.TargetFrequencyValue.ToString();
                drpCFTarget.SelectedValue = existingRiskInstance.TargetControlAffectivenessValue.ToString();

                // Title.
                txtTitle.Text = existingRiskInstance.Title;
                // Desc.
                txtDescription.Text = existingRiskInstance.Desc;

                //Current justification.
                txtCurrentFrequency.Text = existingRiskInstance.CurrentFrequencyJustification;
                txtCurrentCF.Text = existingRiskInstance.CurrentControlAffectivenessJustification;
                txtboxCurrentImpact.Text = existingRiskInstance.CurrentImapctJustification;

                // Target justification.
                txtTargetFreqJustification.Text = existingRiskInstance.TargetFrequencyJustification;
                txtTargetCFjustification.Text = existingRiskInstance.TargetControlAffectivenessJustification;
                txtTargetImpactJustification.Text = existingRiskInstance.TargetImpactJustification;

                // Populate.
                ViewState["organization"] = existingRiskInstance.Organizations;
                ViewState["contact"] = existingRiskInstance.Contacts;

                // Bind the tree for organizations and contacts
                BindorganizationContactTree(existingRiskInstance.OrganizationContact);

                // RiskID
                txtRiskID.Text = existingRiskInstance.RiskID.ToString();

                // Submitted By
                lblsubmittedby.Text = existingRiskInstance.SubmittedByFullName;
                lblSubmittedDate.Text = existingRiskInstance.CreatedDate.ToString();
                lblDelimitor.Visible = true;

                // Bind to check box.
                chkTriage.Checked = existingRiskInstance.RiskValidatedByTriage;

                // Notes
                gridRiskNotes.DataSource = existingRiskInstance.Notes;
                gridRiskNotes.DataBind();
                lblEarlierNotes.Visible = true;

                // Risk Origin Application ID
                if (drpRiskOrgin.SelectedItem.Text.Trim().Equals("SES"))
                {
                    lnkSourceApp.Visible = true;
                    lnkSourceApp.NavigateUrl = ConfigurationManager.AppSettings["SourceSESLink"].ToString() + AntiXss.UrlEncode(existingRiskInstance.RiskOriginApplicationID);
                }
                else if (drpRiskOrgin.SelectedItem.Text.Trim().Equals("MSAPPS"))
                {
                    lnkSourceApp.Visible = true;
                    lnkSourceApp.NavigateUrl = ConfigurationManager.AppSettings["SourceMSAPPSLink"].ToString() + AntiXss.UrlEncode(existingRiskInstance.RiskOriginApplicationID);
                }

                //Risk Wt & PCRV.
                if (existingRiskInstance.RiskPriortizedWt == 0) // to handle old data when this feature was not there.
                    txtRiskWt.Text = "1.0";
                else
                    txtRiskWt.Text = existingRiskInstance.RiskPriortizedWt.ToString();

                if (existingRiskInstance.RiskPriortizedCRV != -1)
                    lblPRCV.Text = existingRiskInstance.RiskPriortizedCRV.ToString();
                else
                    lblPRCV.Text = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();

            }// End of binding the existing Risk to controls.
            else
            {
                drpCFTarget.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForCA"].ToString();
                drpCurrentControlAffectiveness.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForCA"].ToString();
                drpCurrentFrequency.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForFrequency"].ToString();
                drpTargetControlFrequency.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForFrequency"].ToString();
                drpTargetImpact.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForImpact"].ToString();
                drpCurrentImpact.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForImpact"].ToString();
                drpRiskStatus.SelectedValue = ConfigurationManager.AppSettings["DefaultSelectionValueForRiskStatus"].ToString();
                drpPII.SelectedValue = ConfigurationManager.AppSettings["DefaultPII"].ToString();
                drpDataClassification.SelectedValue = ConfigurationManager.AppSettings["DefaultDataClassification"].ToString();
                lstOERMClassification.SelectedValue = ConfigurationManager.AppSettings["DefaultOERM"].ToString();

                // The label should be hidden new Risk UI.
                lblEarlierNotes.Visible = false;
                // Submitted By
                lblsubmittedby.Text = ((CISF.Security.Principal.CISFIdentity)User.Identity).FullName;
                lblDelimitor.Visible = false;
                lblSubmittedDate.Text = string.Empty;
            }


            // Default Values for Current CRV and Risk Rating            
            // FALSE value is flag for Target
            BindRatings(true);

            // Default Values for Target CRV and Risk Rating
            // TRUE value is flag for Current
            BindRatings(false);
        }
        #endregion

        #region Page Error Handling

        public void Page_Error(object sender, EventArgs e)
        {
            System.Exception error = Server.GetLastError();
            throw new HttpException(500, "Unhandled Exception.", error);
        }

        #endregion

        #region Calculation of RR and CRV
        /// <summary>
        /// SOA based rules in the system for calculation of Risk Rating (CR).
        /// </summary>
        /// <param name="impactValue"></param>
        /// <param name="frequencyValue"></param>
        /// <param name="ControlAffectivenessValue"></param>
        /// <returns></returns>
        private string RulesForRiskRating(int impactValue, int frequencyValue, int ControlAffectivenessValue, int currentORTarget)
        {
            RiskService.ManageRiskClient client = new RiskService.ManageRiskClient();
            object riskRating = client.GetRiskRating(impactValue, frequencyValue, ControlAffectivenessValue);
            client.Close();

            string crr = string.Empty;

            if (riskRating == null)
                crr = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
            else
                crr = ((string)riskRating).Trim().ToString();

            if (0 == currentORTarget)
            {
                if (crr.Contains("High"))
                    lblTargetRiskRating.ForeColor = Color.FromName(ConfigurationManager.AppSettings["RRColor"].ToString());
                else
                    lblTargetRiskRating.ForeColor = Color.Empty;
            }
            else
            {
                if (crr.Contains("High"))
                    lblCurrentRiskRating.ForeColor = Color.FromName(ConfigurationManager.AppSettings["RRColor"].ToString());
                else
                    lblCurrentRiskRating.ForeColor = Color.Empty;
            }

            return crr;
        }

        /// <summary>
        /// SOA based rules in the system for calculation of Calculated Risk Rating (CRV).
        /// </summary>
        /// <param name="impactValue"></param>
        /// <param name="frequencyValue"></param>
        /// <param name="ControlAffectivenessValue"></param>
        /// <returns></returns>
        private string RulesForCalculatedRiskValue(int impactValue, int frequencyValue, int ControlAffectivenessValue)
        {
            RiskService.ManageRiskClient client = new RiskService.ManageRiskClient();
            object calculatedRiskValue = client.GetCRV(impactValue, frequencyValue, ControlAffectivenessValue);
            client.Close();

            if (calculatedRiskValue == null)
                return ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
            else
                return ((string)calculatedRiskValue).Trim().ToString();
        }

        #endregion

        #region History

        protected void gvHistory_RowCreated(object sender, GridViewRowEventArgs e)
        {
            int rowIndex = e.Row.RowIndex;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ObjectDataSource ctrl = e.Row.FindControl("obdsHistroyDetail") as ObjectDataSource;
                if (ctrl != null && e.Row.DataItem != null)
                {
                    ctrl.SelectParameters["PersonID"].DefaultValue = gvHistoryMaster.DataKeys[rowIndex].Values[0].ToString();
                    ctrl.SelectParameters["Ticks"].DefaultValue = gvHistoryMaster.DataKeys[rowIndex].Values[1].ToString();
                    ctrl.SelectParameters["RiskID"].DefaultValue = ViewState["RiskID"].ToString();
                }
            }
        }

        private void BindHistory()
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            RiskService.History[] history = riskServiceClient.GetMasterHistoryData(int.Parse(ViewState["RiskID"].ToString()));
            riskServiceClient.Close();

            // BIND to History GRID.
            gvHistoryMaster.DataSource = history;
            gvHistoryMaster.DataBind();
        }

        public HistoryDetail[] GetDetailHistory(int PersonID, long Ticks, int RiskID)
        {
            RiskService.HistoryDetail[] historyDetail = null;
            if (Ticks != 0)
            {
                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
                DateTime dt = new DateTime(Ticks);

                historyDetail = riskServiceClient.GetDetailsHistoryData(RiskID, dt, PersonID);
                riskServiceClient.Close();
            }
            return historyDetail;
        }

        # endregion

        #region Incident Management

        protected void odsSearchIncidents_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            e.InputParameters[0] = int.Parse(ViewState["RiskID"].ToString());

            if (ViewState["Direction"] != null)
                e.InputParameters[1] = ViewState["Direction"].ToString();

            if (ViewState["Sort"] != null)
                e.Arguments.SortExpression = ViewState["Sort"].ToString();
        }

        public Incident[] GetIncidentList(int riskID, string dir, string sortExp)
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            Incident[] list = null;

            list = riskServiceClient.GetIncidentList(riskID, dir, sortExp);
            riskServiceClient.Close();

            return list;
        }

        protected void gvIncidents_Sorting(object sender, GridViewSortEventArgs e)
        {
            // Custom implementation done.
            string sort = e.SortExpression.ToString();
            if (ViewState["Sort"] != null)
            {
                string sortdata = ViewState["Sort"].ToString();
                char[] ch = { ' ' };
                string[] sorting = sortdata.Split(ch);
                if (sorting[0] == e.SortExpression.ToString())
                {
                    if (ViewState["Direction"] == null)
                        ViewState["Direction"] = "ASC";
                    else
                    {
                        if (ViewState["Direction"].ToString() == "ASC")
                            ViewState["Direction"] = "DESC";
                        else
                            ViewState["Direction"] = "ASC";
                    }
                }
            }
            else
            {
                ViewState["Direction"] = "ASC";
            }
            sort = e.SortExpression;
            ViewState["Sort"] = sort;

            // reset the idex and visibility.
            pnlIncidentData.Visible = false;
            gvIncidents.SelectedIndex = -1;
            DataBindIncidents();
        }

        private void DataBindIncidents()
        {
            gvIncidents.DataSource = odsSearchIncidents;
            gvIncidents.DataBind();
        }

        protected void gvIncidents_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvIncidents.PageIndex = e.NewPageIndex;
            DataBindIncidents();
            gvIncidents.SelectedIndex = -1;
            pnlIncidentData.Visible = false;
        }

        protected void gvIncidents_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (gvIncidents.SelectedValue == null)
                pnlIncidentData.Visible = false;
            else
            {
                pnlIncidentData.Visible = true;
                PopulateIncidentData();
            }
        }

        private void PopulateIncidentData()
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            RiskService.Incident incedentInstance = riskServiceClient.GetSingleIncidentData(int.Parse(ViewState["RiskID"].ToString()), int.Parse(gvIncidents.DataKeys[gvIncidents.SelectedIndex].Value.ToString()));
            riskServiceClient.Close();

            // Bind Data
            txtIncidentdentTitle.Text = incedentInstance.Title;
            txtIncidentDescription.Text = incedentInstance.Desc;
            txtIncidentIdentifier.Text = incedentInstance.IncidentID.ToString();
            txtSubmittedByIncident.Text = incedentInstance.SubmittedBy;
        }

        protected void btnUpdateIncident_Click(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsValid)
                    throw new Exception("Custom:" + UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "SERVER_VALIDATIONFAILED"));


                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
                riskServiceClient.UpdatetIncident(int.Parse(ViewState["RiskID"].ToString()), txtIncidentdentTitle.Text, txtIncidentDescription.Text, ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId, int.Parse(txtIncidentIdentifier.Text));
                riskServiceClient.Close();

                UTL.Utility.ShowMessage((MasterPage)Master, UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "INCIDENT_UPDATESUCCESS"), "Information", false);

                DataBindIncidents();
            }
            catch (Exception exObject)
            {
                char[] err = { ':' };
                string[] messages = exObject.Message.Split(err);
                if (messages[0].Trim().ToString() == "Custom")
                {
                    //Read the Resource file.
                    UTL.Utility.ShowMessage((MasterPage)Master, messages[1], "Error", true);
                    Server.ClearError();
                }
                else
                    throw exObject;
            }

        }

        protected void btnInsertIncident_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Server side validation.
                if (!Page.IsValid)
                    throw new Exception("Custom:" + UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "SERVER_VALIDATIONFAILED"));

                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
                riskServiceClient.InsertIncident(int.Parse(ViewState["RiskID"].ToString()), txtpopTitle.Text, txtpopDesc.Text, ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                riskServiceClient.Close();

                // Refresh the grid.
                DataBindIncidents();

                txtpopTitle.Text = string.Empty;
                txtpopDesc.Text = string.Empty;

                // Clean up the main page.
                pnlIncidentData.Visible = false;
                gvIncidents.SelectedIndex = -1;
            }
            catch (Exception exObject)
            {
                char[] err = { ':' };
                string[] messages = exObject.Message.Split(err);
                if (messages[0].Trim().ToString() == "Custom")
                {
                    Page pge = (Page)this.Page;
                    Type cstype = this.GetType();
                    //Read the resource file.
                    UTL.Utility.ShowMessage((MasterPage)Master, messages[1], "Error", true);
                    Server.ClearError();
                }
                else
                    throw exObject;
            }
        }

        #endregion

        #region Chart for Calculated Risk Value

        protected void drpfilterforChart_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindToChart();
        }

        /// <summary>
        ///  Bind data to CHART.
        /// </summary>
        protected void BindToChart()
        {
            // Get data from using service layer.
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            DataSet dsPoints = riskServiceClient.GetCalculatedCRVDataSet(int.Parse(ViewState["RiskID"].ToString()), 0);
            riskServiceClient.Close();
            // Rows
            int rowsCount = dsPoints.Tables[0].Rows.Count;
            if (rowsCount != 0)
            {
                chartCRV.Visible = true;
                lblchartfliter.Visible = true;
                lblChartMessage.Visible = false;


                chartCRV.Series.Clear();
                // Create new data series and set it's visual attributes
                Series series = new Series("CRVValue");
                series.ChartType = SeriesChartType.Line;

                series.BorderWidth = 2;
                series.ShadowOffset = 1;
                series.Color = System.Drawing.Color.FromName(ConfigurationManager.AppSettings["ChartLineColorCRV"].ToString());




                // Empty data point Handling.                
                series.EmptyPointStyle.BorderDashStyle = ChartDashStyle.Dash;
                series.EmptyPointStyle.BorderWidth = 2;
                series.EmptyPointStyle.Color = System.Drawing.Color.Salmon;
                series.EmptyPointStyle.MarkerStyle = MarkerStyle.None;
                series["EmptyPointValue"] = "Average";

                // Bind data to chart.
                series.Points.DataBindXY(dsPoints.Tables[0].DefaultView, "CreatedDate", dsPoints.Tables[0].DefaultView, "CRVValue");

                // Add series into the chart's series collection
                chartCRV.Series.Add(series);
                chartCRV.BackHatchStyle = ChartHatchStyle.Percent50;

                /*
                chartCRV.Legends["Default"].BackColor = Color.Transparent;                
                chartCRV.Legends["Default"].BorderColor = Color.Black;
                chartCRV.Legends["Default"].BorderWidth = 1;
                chartCRV.Legends["Default"].BorderDashStyle = ChartDashStyle.Solid;
                 */

                // Set axis title
                chartCRV.ChartAreas[0].AxisY.Title = "Current CRV";
                chartCRV.ChartAreas[0].AxisY.TitleFont = new Font("verdana", 8);


                // Lables
                chartCRV.ChartAreas[0].AxisX.IsLabelAutoFit = true;
                this.chartCRV.ChartAreas[0].AxisX.LabelStyle.Format = "dd,MMM";
                chartCRV.ChartAreas[0].AxisX.LabelAutoFitStyle =
            LabelAutoFitStyles.DecreaseFont | LabelAutoFitStyles.IncreaseFont | LabelAutoFitStyles.LabelsAngleStep30 | LabelAutoFitStyles.StaggeredLabels;

                // Set interval of X axis to zero, which represents an "Auto" value.
                chartCRV.ChartAreas[0].AxisX.Interval = 0;
                // Use variable count algorithm to generate labels.                
                chartCRV.ChartAreas[0].AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;

                // Set logarithmic base    
                chartCRV.ChartAreas[0].AxisY.LogarithmBase = 10;
                chartCRV.ChartAreas[0].AxisY.IsLogarithmic = true;

                chartCRV.ChartAreas[0].BackColor = Color.SkyBlue;

                // Marker
                chartCRV.Series[0].MarkerStyle = MarkerStyle.Diamond;
                chartCRV.Series[0].MarkerColor = System.Drawing.Color.FromName(ConfigurationManager.AppSettings["ChartMarker"].ToString());
                chartCRV.Series[0].MarkerSize = 5;
            }
            else
            {
                chartCRV.Visible = false;
                lblChartMessage.Visible = true;
                lblchartfliter.Visible = false;
            }
        }

        #endregion

        #region Contact

        protected void btnSubmitContact_Clicked(object sender, EventArgs e)
        {
            string contact = txtfindContact.Text.Split('(')[0].Trim();
            object personID = null;
            //Check for a valid contact

            // Check for empty.
            if (!string.IsNullOrEmpty(contact))
            {
                //Stringbuilder for better performance.
                StringBuilder finalconcatenatedList = new StringBuilder(250); // This will not have duplicates.

                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
                personID = riskServiceClient.GetPersonID(contact);

                if (personID != null)
                {
                    contact = personID.ToString() + ",";

                    if (ViewState["contact"] == null)
                        ViewState["contact"] = contact;
                    else
                        ViewState["contact"] = ViewState["contact"].ToString() + contact;

                    if (ViewState["organization"] == null)
                        ViewState["organization"] = string.Empty;

                    string temp = ViewState["contact"].ToString().Trim();
                    temp = temp.Substring(0, temp.Length - 1); // remove last comma.

                    string[] canHaveDuplicatesOrganizations = temp.Split(',');

                    // Extract distinct.
                    List<string> final = new List<string>();
                    final.AddRange(canHaveDuplicatesOrganizations.Distinct<string>());

                    // Concatenate again to build string.
                    foreach (string hold in final)
                        finalconcatenatedList.Append(hold + ",");

                    ViewState["contact"] = finalconcatenatedList.ToString();

                    // CALL SOA layer to get XML
                    OrganizationContact orgContact = riskServiceClient.GetOrganizationContactXML(ViewState["organization"].ToString(), ViewState["contact"].ToString());
                    riskServiceClient.Close();

                    // Bind the data to tree control.
                    BindorganizationContactTree(orgContact);

                    txtfindContact.Text = string.Empty;
                }
                else
                {
                    //Read the Resource file.      
                    UTL.Utility.ShowMessage((MasterPage)Master, UTL.Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.RiskMessages", "RISK_INVALIDUSER"), "Error", true);
                    txtfindContact.Text = string.Empty;
                }
            }
            mpeAddcontact.Show();
        }

        #endregion

        #region Organization

        protected void btnSubmitOrganizations_Clicked(object sender, EventArgs e)
        {
            TreeNodeCollection nodecollection = treeOrganization.CheckedNodes;
            StringBuilder concatenatedList = new StringBuilder(250); // Better performance than string Type.            
            StringBuilder finalconcatenatedList = new StringBuilder(250); // This will not have duplicates.

            /// Get Selected Organizations.
            foreach (TreeNode tree in nodecollection)
                concatenatedList.Append(tree.Value + ",");

            if (ViewState["organization"] == null)
                ViewState["organization"] = concatenatedList.ToString();
            else
                ViewState["organization"] = ViewState["organization"].ToString() + concatenatedList.ToString();

            string temp = ViewState["organization"].ToString().Trim();
            temp = temp.Substring(0, temp.Length - 1); // remove last comma.

            string[] canHaveDuplicatesOrganizations = temp.Split(',');

            // Extract distinct.
            List<string> final = new List<string>();
            final.AddRange(canHaveDuplicatesOrganizations.Distinct<string>());

            // Concatenate again to build string.
            foreach (string hold in final)
                finalconcatenatedList.Append(hold + ",");

            ViewState["organization"] = finalconcatenatedList.ToString();

            if (ViewState["contact"] == null)
                ViewState["contact"] = string.Empty;

            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // CALL SOA layer to get XML
            OrganizationContact orgContact = riskServiceClient.GetOrganizationContactXML(ViewState["organization"].ToString(), ViewState["contact"].ToString());
            riskServiceClient.Close();

            // Bind the data to tree control.
            BindorganizationContactTree(orgContact);

            //Reset                      
            treeOrganization.Nodes[0].ChildNodes.Clear();
            // Needed for both new and old.
            GetRootLevelBind();
            treeOrganization.ExpandDepth = 1;
        }

        /// <summary>
        /// Helper function to bind data to tree and orphaned people.
        /// </summary>
        private void BindorganizationContactTree(OrganizationContact orgContact)
        {
            treeOrganizationContact.Nodes.Clear();
            string newRootXML = string.Empty;
            XmlDocument newRoot = null;
            XmlDocument olddoc = null;

            if (!string.IsNullOrEmpty(orgContact.OrganizationContactXML))
            {

                olddoc = new XmlDocument();
                olddoc.LoadXml(orgContact.OrganizationContactXML);

                newRoot = new XmlDocument();
                newRoot.LoadXml("<" + ConfigurationManager.AppSettings["RootNode"].ToString() + "/>");
                newRoot.DocumentElement.InnerXml = olddoc.DocumentElement.InnerXml;
                newRootXML = newRoot.OuterXml;
                olddoc = null;
                newRoot = null;

                // Bind to XML string.
                string xmlSource = newRootXML;
                customSource.Data = xmlSource;

                // Bind to xml data source.            
                treeOrganizationContact.DataSource = customSource;
                treeOrganizationContact.DataBind();

                // Create Others. New Root Node.
                BindDefaultNodes(true);
            }
            else
                // Create Others.
                BindDefaultNodes(false);

            // binding orphanded contacts to "Others"
            RiskService.Person[] people = orgContact.OrphanedContacts;
            TreeNode node = treeOrganizationContact.FindNode(ConfigurationManager.AppSettings["RootNode"].ToString() + "/" + ConfigurationManager.AppSettings["OrphanedNode"].ToString().Trim());

            // Loop through all people and bind to Others.
            foreach (Person temp in people)
                node.ChildNodes.Add(new TreeNode(temp.FullName, temp.PersonID.ToString(), "../Images/online.gif"));
        }

        protected void PopulateNode(Object source, TreeNodeEventArgs e)
        {
            switch (e.Node.Depth)
            {
                case 0:
                    GetRootLevelBind();
                    break;
                case 1:
                    GetNextLevelBind(e.Node);
                    break;
                case 2:
                    GetNextLevelBind(e.Node);
                    break;
                case 3:
                    GetNextLevelBind(e.Node);
                    break;
                case 4:
                    GetNextLevelBind(e.Node);
                    break;
                case 5:
                    GetNextLevelBind(e.Node);
                    break;
            }
        }

        protected void GetRootLevelBind()
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            RiskService.OrganizationData[] orgList = riskServiceClient.GetRootLevel();
            riskServiceClient.Close();

            // Custom text for root.
            treeOrganization.Nodes[0].Text = ConfigurationManager.AppSettings["RootNode"].ToString();
            TreeNode root = treeOrganization.Nodes[0];

            foreach (OrganizationData temp in orgList)
            {
                TreeNode newNode = new TreeNode(temp.OrgnaizationName, temp.OrgnaizationID.ToString());
                newNode.SelectAction = TreeNodeSelectAction.Expand;
                newNode.PopulateOnDemand = true;
                // Bind Child.    
                root.ChildNodes.Add(newNode);
            }
        }

        protected void GetNextLevelBind(TreeNode node)
        {
            String nodeID = node.Value;
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            RiskService.OrganizationData[] orgList = riskServiceClient.GetNextLevelOrganizations(int.Parse(nodeID));
            riskServiceClient.Close();

            foreach (OrganizationData temp in orgList)
            {
                TreeNode newNode = new TreeNode(temp.OrgnaizationName, temp.OrgnaizationID.ToString());
                newNode.PopulateOnDemand = true;
                node.ChildNodes.Add(newNode);
            }
        }

        protected void BindDefaultNodes(bool flag)
        {
            if (flag)
            {
                // Remove check box from Root Node.
                TreeNode root = treeOrganizationContact.Nodes[0];
                root.ShowCheckBox = false;
                root.ExpandAll();


                // Append Others
                TreeNode others = new TreeNode(ConfigurationManager.AppSettings["OrphanedNode"].ToString().Trim());
                others.Checked = false;
                root.ChildNodes.Add(others);

                treeOrganizationContact.ExpandAll();
            }
            else
            {
                // Remove check box from Root Node.
                TreeNode root = new TreeNode(ConfigurationManager.AppSettings["RootNode"].ToString());
                root.ShowCheckBox = false;

                // Append Others
                TreeNode others = new TreeNode(ConfigurationManager.AppSettings["OrphanedNode"].ToString().Trim());
                others.Checked = false;
                root.ChildNodes.Add(others);

                // Bind to tree view.
                treeOrganizationContact.Nodes.Add(root);
                treeOrganizationContact.ExpandAll();
            }
        }

        protected void btnDeleteOrganizationContact_Click(object sender, EventArgs e)
        {
            List<TreeNode> nodeCollection = FetchAllNodes(treeOrganizationContact);

            string newOrgnaization = string.Empty;
            string newContact = string.Empty;

            foreach (TreeNode temp in nodeCollection)
            {
                if (temp.Depth == 2 && (!temp.Checked))
                    newContact += temp.Value + ",";

                if ((temp.Depth == 1) && (temp.Text != ConfigurationManager.AppSettings["OrphanedNode"].ToString()) && (!temp.Checked))
                    newOrgnaization += temp.Value + ",";
            }

            ViewState["organization"] = newOrgnaization;
            ViewState["contact"] = newContact;

            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // CALL SOA layer to get XML
            OrganizationContact orgContact = riskServiceClient.GetOrganizationContactXML(ViewState["organization"].ToString(), ViewState["contact"].ToString());
            riskServiceClient.Close();

            // Bind the data to tree control.
            BindorganizationContactTree(orgContact);
        }

        #endregion

        #region Helper Function

        /// <summary>
        /// Bind to DropDown.
        /// </summary>
        /// <param name="drpControl"></param>
        /// <param name="collection"></param>
        private void BindToDropDownList(DropDownList drpControl, ListItem[] collection)
        {
            foreach (ListItem temp in collection)
            {
                drpControl.Items.Add(new ListItem(temp.Text, temp.Value));
            }
        }
        /// <summary>
        /// To bind CRV and Risk Ratings for Risk.
        /// </summary>
        /// <param name="flagforCurrent"></param>
        private void BindRatings(bool flagforCurrentRiskValues)
        {
            if (flagforCurrentRiskValues)
            {
                // Default Values for Current CRV and Risk Rating
                int currentImpactValue = int.Parse(drpCurrentImpact.SelectedItem.Text.Trim().Split('-')[0].ToString());
                int currentCAValue = int.Parse(drpCurrentControlAffectiveness.SelectedItem.Text.Trim().Split('-')[0].ToString());
                int currentFrequencyValue = int.Parse(drpCurrentFrequency.SelectedItem.Text.Trim().Split('-')[0].ToString());

                lblCurrentRiskRating.Text = RulesForRiskRating(currentImpactValue, currentFrequencyValue, currentCAValue, 1);
                lblCurrentCRV.Text = RulesForCalculatedRiskValue(currentImpactValue, currentFrequencyValue, currentCAValue);

                Decimal wt;
                bool checkDecimal = Decimal.TryParse(txtRiskWt.Text.Trim(), out wt);

                if (!checkDecimal)
                    txtRiskWt.Text = "1.0"; // Populate with default to 1.0.    

                wt = Decimal.Round(Decimal.Parse(txtRiskWt.Text.Trim()), 1);
                txtRiskWt.Text = wt.ToString();

                if (!string.Equals(lblCurrentCRV.Text.Trim(), ConfigurationManager.AppSettings["DefaultTextRatings"].ToString()))
                {
                    lblPRCV.Text = RulesForPCRV(int.Parse(lblCurrentCRV.Text), Decimal.Parse(txtRiskWt.Text));
                }
                else
                    lblPRCV.Text = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
            }
            else
            {
                // Default Values for Target CRV and Risk Rating
                int targetImpactValue = int.Parse(drpTargetImpact.SelectedItem.Text.Trim().Split('-')[0].ToString());
                int targetCAValue = int.Parse(drpCFTarget.SelectedItem.Text.Trim().Split('-')[0].ToString());
                int targetFrequencyValue = int.Parse(drpTargetControlFrequency.SelectedItem.Text.Trim().Split('-')[0].ToString());

                lblTargetRiskRating.Text = RulesForRiskRating(targetImpactValue, targetFrequencyValue, targetCAValue, 0);
                lblTargteRiskRatingValue.Text = RulesForCalculatedRiskValue(targetImpactValue, targetFrequencyValue, targetCAValue);
            }
        }

        private string RulesForPCRV(int crv, Decimal wt)
        {
            try
            {
                RiskService.ManageRiskClient client = new RiskService.ManageRiskClient();
                object calculatedPRiskValue = client.GetPCRV(crv, wt);
                client.Close();

                if (calculatedPRiskValue == null)
                    return ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
                else
                    return calculatedPRiskValue.ToString();
            }
            catch (Exception exObject)
            {
                char[] err = { ':' };
                string[] messages = exObject.Message.Split(err);
                if (messages[0].Trim().ToString() == "Custom")
                {
                    Page pge = (Page)this.Page;
                    Type cstype = this.GetType();
                    // Display the message.
                    UTL.Utility.ShowMessage((MasterPage)Master, messages[1], "Error", true);
                    Server.ClearError();
                }
                else
                    throw exObject;
            }
            return ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
        }

        public void TxtCalculatePCRV(Object sender, EventArgs e)
        {
            Decimal wt;
            bool checkDecimal = Decimal.TryParse(txtRiskWt.Text.Trim(), out wt);

            if (!checkDecimal)
                txtRiskWt.Text = "1.0"; // Populate with default to 1.0.                   
            wt = Decimal.Round(Decimal.Parse(txtRiskWt.Text.Trim()), 1);
            txtRiskWt.Text = wt.ToString();

            if (!string.Equals(lblCurrentCRV.Text.Trim(), ConfigurationManager.AppSettings["DefaultTextRatings"].ToString()))
            {
                lblPRCV.Text = RulesForPCRV(int.Parse(lblCurrentCRV.Text), Decimal.Parse(txtRiskWt.Text));
            }
            else
                lblPRCV.Text = ConfigurationManager.AppSettings["DefaultTextRatings"].ToString();
        }

        /// <summary>    
        /// Flattens all the nodes in a tree view using    
        /// a stack based depth first search.    
        /// </summary>    
        /// <param name="tree"></param>    
        /// <returns></returns>    
        public List<TreeNode> FetchAllNodes(TreeView tree)
        {
            List<TreeNode> nodes = new List<TreeNode>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            // Add all the top nodes into the queue.        
            foreach (TreeNode top in tree.Nodes)
            {
                stack.Push(top);
            }
            while (stack.Count > 0)
            {
                TreeNode node = stack.Pop();
                if (node != null)
                {
                    //                
                    // Add the node to the list of nodes.               
                    //                
                    nodes.Add(node);
                    if (node.ChildNodes != null && node.ChildNodes.Count > 0)
                    {
                        //                    
                        // Enqueue the child nodes.                    
                        //                    
                        foreach (TreeNode child in node.ChildNodes)
                        {
                            stack.Push(child);
                        }
                    }
                }
            }
            return nodes;
        }

        /// <summary>
        /// Role based check for diplaying UI.
        /// </summary>
        private void RoleBasedCheck()
        {
            // The user is just TTU.
            if ((bool)ViewState["readOnlyORnoAccess"] == true)
            {
                btnSubmitRisk.Visible = false;
                btnAddcontact.Visible = false;
                btnOrganization.Visible = false;
                btnDeleteOrganizationContact.Visible = false;

                // Hide the tabs.
                tabRiskIncidents.Visible = false;
                tabRiskHistory.Visible = false;

                //Disable the manager stuff here.
                drpRiskStatus.Enabled = false;
                drpManager.Enabled = false;
                tabCommitment.Enabled = false;

                if (ViewState["RiskID"] != null)
                    // Enable Task Tab
                    createViewTasks.RiskID = int.Parse(ViewState["RiskID"].ToString());

            }
            else // The user is RM or RU.
            {
                // Display.
                btnAddcontact.Visible = true;
                btnOrganization.Visible = true;
                btnDeleteOrganizationContact.Visible = true;
                btnSubmitRisk.Visible = true;

                // Role based access & correct.
                if (this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskManager"].ToString()))
                {
                    // Do not use Risk Configuration. The user is RM.
                    ViewState["RiskConfiguration"] = 0;

                    drpRiskStatus.Enabled = true;
                    drpManager.Enabled = true;
                    tabCommitment.Enabled = true;
                    reqDrpManager.Enabled = true;

                    if (ViewState["RiskID"] != null)
                    {
                        drpManager.Visible = true;
                        lblRiskManager.Visible = true;
                        tabTaskManagement.Visible = true;
                        lblManager.Visible = true;
                        // Enable Task Tab
                        createViewTasks.RiskID = int.Parse(ViewState["RiskID"].ToString());
                    }
                    else
                        tabTaskManagement.Visible = false;  
                }
                else // The user is RU and not RM.
                {
                    ViewState["RiskConfiguration"] = 1;

                    drpRiskStatus.Enabled = false;
                    drpManager.Enabled = false;
                    tabCommitment.Enabled = false;
                    // Task Management Tab is not shown for Risk User.
                    tabTaskManagement.Visible  = false;
                    reqDrpManager.Enabled = false;

                    if (ViewState["RiskID"] == null)
                    {
                        drpManager.Visible = false;
                        lblRiskManager.Visible = false;
                        lblManager.Visible = false;
                    }
                }

                // Based on Risk is new or existing the tabs will be displayed.
                if (ViewState["RiskID"] != null)
                {
                    tabRiskIncidents.Visible = true;
                    tabRiskHistory.Visible = true;                    
                }
                else
                {
                    tabRiskIncidents.Visible = false;
                    tabRiskHistory.Visible = false;                    
                }
            }
        }

        /// <summary>
        /// Reterives the Concatenated string of values.
        /// </summary>
        /// <param name="lstControl"></param>
        /// <returns></returns>
        private string GetConcatenatedString(ListBox lstControl)
        {
            StringBuilder concatenated = new StringBuilder(250);
            foreach (ListItem lsttemp in lstControl.Items)
            {
                if (lsttemp.Selected)
                    concatenated.Append(lsttemp.Value + ",");
            }
            return concatenated.ToString();
        }

        private void GetDataForManager()
        {
            // Bind to Risk Manager drop down.
            AuthZService.AuthZServiceClient aClient = new AuthZService.AuthZServiceClient();
            Microsoft.InformationSecurity.CISF.Security.AuthZServices.User[] users = aClient.GetUsersInRole(ConfigurationManager.AppSettings["RiskManager"].ToString());
            aClient.Close();
            drpManager.Items.Clear();
            
            // Source Fields
            drpManager.DataSource = users;
            drpManager.DataTextField = "FullName";
            drpManager.DataValueField = "PersonID";
            drpManager.DataBind();
            drpManager.Items.Insert(0, new ListItem("", ""));
        }

        /// <summary>
        /// Helper function to re verify that user has acccess to view the risk if the user is not RM or RU.
        /// </summary>
        /// <returns></returns>
        private bool UserHasAcccess()
        {
            bool flag = false;
            int count = GetSearchResultCount("Risk ID", "=", null, 0, ViewState["RiskID"].ToString(), null, ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId, 0);

            if (count == 1)
                flag = true;
            else
                flag = false;

            return flag;
        }

        /// <summary>
        /// Get the count for the search records found.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldoperator"></param>
        /// <param name="sortField"></param>
        /// <param name="sortAscDesc"></param>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <returns></returns>
        private int GetSearchResultCount
            (
            string fieldName,
            string fieldoperator,
            string sortField,
            int sortAscDesc,
            string value1,
            string value2,
            int personID,
            int isRoleFilter
            )
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // Declare local variables.
            int totalCount = riskServiceClient.BasicSearchRiskCount
                (
                fieldName,
                fieldoperator,
                value1,
                value2,
                personID,
                isRoleFilter
                );
            riskServiceClient.Close();

            return totalCount;
        }
        #endregion        
    }
}
